
import { defineStore } from 'pinia'
import { nextTick } from 'vue'

const getStorage = name => {
  const data = window.localStorage.getItem(name)
  try {
    return JSON.parse(data)
  } catch (err) {
    return data
  }
}

const setStorage = (name, value) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }

  window.localStorage.setItem(name, value)
}

const removeStorage = name => {
  window.localStorage.removeItem(name)
}

const themeKey = 'theme'

const defaultConfig = {
  elColorPrimary: '#167EFF',
  dwSidebaBg: '#202938'
}

export const useThemeStore = defineStore({
  id: 'theme',
  state: () => ({
    isDark: getStorage('vueuse-color-scheme') === true || false,
    themeJson: getStorage(themeKey) || { ...defaultConfig }
  }),
  getters: {},
  actions: {
    /* 设置主题模式 */
    setDarkModel (model) {
      nextTick(() => {
        this.isDark = model
        if (this.isDark) {
          document.documentElement.classList.add('dark')
        } else {
          document.documentElement.classList.remove('dark')
        }
        setStorage('vueuse-color-scheme', this.isDark)
      })
    }
  }
})
